# Copyright 2018 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare, float_round
import logging
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)


class StockMove(models.Model):
    _inherit = 'stock.move'

    def _prepare_account_move_line(self, qty, cost, credit_account_id, debit_account_id):
        """
        Generate the account.move.line values to post to track the stock valuation difference due to the
        processing of the given quant.
        """
        self.ensure_one()

        if self._context.get('force_valuation_amount'):
            valuation_amount = self._context.get('force_valuation_amount')
        else:
            valuation_amount = cost

        # the standard_price of the product may be in another decimal precision, or not compatible with the coinage of
        # the company currency... so we need to use round() before creating the accounting entries.
        debit_value = self.company_id.currency_id.round(valuation_amount)

        # check that all data is correct
        # _logger.info('_prepare_account_move_line')
        if self.company_id.currency_id.is_zero(debit_value):
            # _logger.info('is_zero')
            if(not self.purchase_line_id):  # 如果不是采购，就不判断零
                # _logger.info('not self.purchase_line_id')
                pass
            elif(not self.purchase_line_id.borrow):  # 如果是采购，就判断是不是借货，既允许是零
                # _logger.info('not self.purchase_line_id borrow')
                raise UserError(_("The cost of %s is currently equal to 0. Change the cost or the configuration of your product to avoid an incorrect valuation.") % (
                    self.product_id.display_name,))
        credit_value = debit_value

        valuation_partner_id = self._get_partner_id_for_valuation_lines()
        res = [(0, 0, line_vals) for line_vals in self._generate_valuation_lines_data(
            valuation_partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id).values()]
        # _logger.info(res)
        return res
